﻿using System;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Data.Objects;
using System.Collections;
using HanGu.Entity;
using HanGu.Entity.Enum;

namespace HanGu.Dal
{
   public class BaseDAL
    {
        #region 数据操作方法
        //创建数据库连接
        //public HaiGuEntities dbConn;

        /// <summary>
        ///  在构造函数中初始化数据库连接
        /// </summary>
       public BaseDAL()
        {
            //dbConn = new HaiGuEntities();
        }

        /// <summary>
        /// 新增实体信息
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected TEntity Add<TEntity>(TEntity entity)
        {
            using(HaiGuEntities dbConn = new HaiGuEntities())
            {
                try
                {
                    dbConn.AddObject(entity.GetType().Name, entity);
                    dbConn.SaveChanges();
                    return entity;
                }
                catch (Exception e)
                {
                    ExceptionHand(e);

                    return entity;
                }               
            }
           
        }

        /// <summary>
        /// 修改实体信息
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected TEntity Update<TEntity>(TEntity entity) where TEntity : class
        {
            using (HaiGuEntities dbConn = new HaiGuEntities())
            {
                try
                {
                    var key = dbConn.CreateEntityKey(entity.GetType().Name, entity);
                    object obj;
                    if (dbConn.TryGetObjectByKey(key, out obj))
                    {
                        dbConn.ApplyCurrentValues<TEntity>(entity.GetType().Name, entity);
                    }
                    else
                    {
                        dbConn.AttachTo(entity.GetType().Name, entity);
                    }
                    dbConn.SaveChanges();
                    return entity;
                }
                catch (Exception e)
                {
                    ExceptionHand(e);

                    return entity;
                }
            }
          
           
        }

       

        /// <summary>
        /// 根据条件，删除一个实体
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="condition"></param>
        /// <returns></returns>
        public TEntity Delete<TEntity>(Expression<Func<TEntity, bool>> where) where TEntity : EntityObject
        {
            using (HaiGuEntities dbConn = new HaiGuEntities())
            {
                TEntity entity = null;
                try
                {                    
                    entity = dbConn.CreateObjectSet<TEntity>().Where(where).FirstOrDefault();

                    dbConn.DeleteObject(entity);
                    dbConn.SaveChanges();
                    return entity;
                }
                catch (Exception e)
                {
                    ExceptionHand(e);

                    return entity;
                }
               
            }
           
        }

        /// <summary>
        /// 根据条件查询，返回一个实体
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="condition"></param>
        /// <returns></returns>
        public TEntity GetBy<TEntity>(Expression<Func<TEntity, bool>> condition) where TEntity : EntityObject
        {
            using (HaiGuEntities dbConn = new HaiGuEntities())
            {
                TEntity entity = null;
                try
                {
                    entity = dbConn.CreateObjectSet<TEntity>().Where(condition).FirstOrDefault();
                    return entity;
                }
                catch (Exception e)
                {
                    ExceptionHand(e);

                    return entity;
                }
              
            }
            
        }

        /// <summary>
        /// 根据固定条件查询，返回一个实体集合
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<TEntity> GetList<TEntity,TOrderBy>(Expression<Func<TEntity, bool>> condition, Expression<Func<TEntity, TOrderBy>> orderby) 
            where TEntity : EntityObject
            where TOrderBy : class
        {
            using (HaiGuEntities dbConn = new HaiGuEntities())
            {
                try
                {
                    return dbConn.CreateObjectSet<TEntity>().Where(condition).OrderBy(condition).ToList<TEntity>();
                }
                catch (Exception e)
                {
                    ExceptionHand(e);

                    return null;
                }
            }           
           
        }
        #endregion

        #region 日志记录

        protected void ExceptionHand(Exception e)
        {
            string title = this.ToString() + e.TargetSite;
            string message = e.Source + "_" + e.Message + Environment.NewLine + e.StackTrace;
            WriteGeneralLog(title, message, Priority.Normal);
            throw e;
        }
        
        /// <summary>
        /// 异常错误日志记录
        /// </summary>
        /// <param name="p_Title">标题</param>
        /// <param name="p_Message">内容</param>
        /// <param name="p_Priority">级别</param>
        /// <returns></returns>
        public void WriteGeneralLog(string p_Title, string p_Message, Priority p_Priority)
        {
            try
            {
                this.WriteLog(p_Title, p_Message, p_Priority, Category.General);
            }
            catch (Exception e)
            { 
                throw e; 
            }
        }
        
        /// <summary>
        /// 跟踪日志记录
        /// </summary>
        /// <param name="p_Title">标题</param>
        /// <param name="p_Message">内容</param>
        /// <param name="p_Priority">级别</param>
        /// <returns></returns>
        public void WriteTraceLog(string p_Title, string p_Message, Priority p_Priority)
        {
            try
            {
                this.WriteLog(p_Title, p_Message, p_Priority, Category.Trace);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private void WriteLog(string p_Title, string p_Message, Priority p_Priority, string p_Category)
        {
            try
            {
                int priority = (int)p_Priority;
                string category = p_Category.ToString();

                LogEntry logEntry = new LogEntry();

                logEntry.TimeStamp = DateTime.Now;
                logEntry.Title = p_Title;
                logEntry.Message = p_Message;
                logEntry.Priority = priority;
                logEntry.Categories.Add(category);

                Logger.Write(logEntry, category);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion
    }
}
